<template>
  <TreeSelect
    v-model="departmentId"
    :treeProps="defaultProps"
    :treeData="departmentTree"
  />
</template>
<script lang="ts" setup>
/*
*部门下拉树形菜单
*/
import TreeSelect from '@/components/TreeSelect.vue';
import {
  getCurrentInstance, ref, isRef, onMounted, defineProps, computed, withDefaults,
} from 'vue';

const { proxy } = getCurrentInstance(); // 使用proxy代替ctx，因为ctx只在开发环境有效
// 加载部门属性菜单
interface Tree { // 树形接口类型
  id:number;
  name: string;
  children?: Tree[];
}

interface Props {
  modelValue: any,
  data?: Array<Tree>|null,
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => null,
});

const defaultProps = { // 部门树形菜单显示标签对应的属性名
  value: 'id',
  label: 'name',
  children: 'children',
};
// 从服务端获取部门树形菜单数据
const departmentTree = ref<Tree[]>([]);// 定义部门树形菜单
const getDepartmentTree = async () => { // 读取部门树形菜单
  const resData:any = await new proxy.$Request(proxy.$urls.API_URL_BACKSTAGE_DEPARTMENT_TREE).get();
  console.log(resData.success);
  if (resData.success) {
    console.log(1);
    departmentTree.value = resData.data;
  }
};
if (props.data == null) { // 如果没有值传进来
  onMounted(getDepartmentTree);
} else {
  departmentTree.value = [];
}

// 对部门属性进行监听
const departmentId = ref(computed({
  get() { // 不能在get里面改变nodeName.value的值，所以在watch里面进行修改
    // nodeName.value=treeRef.value.getNode(props.modelValue).data["name"];
    return props.modelValue;
  },
  set(val) {
    proxy.$emit('update:modelValue', val);// 则传递给父组件
  },
}));
</script>
